/**************************************************************
  > File Name: du_opendir.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2021年12月19日 星期日 12时42分02秒
 **************************************************************/

#include "pthread_pool.h"

#define BUFSIZE 1024
#define PTHREADNUM 5

pthread_pool pool;

//判断是否为..和.
static int is_loop(const char *pathname)
{
	char *pos = NULL;
	pos = strrchr(pathname,'/');
	if (pos == NULL)
		exit(1);
	if ((strcmp(pos+1,".") == 0) || (strcmp(pos+1,"..") == 0))
		return 1;
	return 0;
}

static void myCopy(void *argc)
{
	FILE *fps, *fpd;
	struct fileNode *node = (struct fileNode *)argc;

	fps = fopen(node->src, "r");
	if (fps == NULL)
	{
		perror("fopen()");
		exit(1);
	}

	fpd = fopen(node->dest, "w");
	if (fpd == NULL)
	{
		perror("fopen()");
		exit(1);
	}
		
	char buf[BUFSIZE] = {0};
	int len;

	while ((len = fread(buf, sizeof(char), BUFSIZE, fps)) > 0)
	{
		fwrite(buf, sizeof(char), len, fpd);
	}
	fclose(fpd);
	fclose(fps);
}

void func(const char *srcName, const char *destName)
{
	DIR *dir = NULL;
	pthread_t tid;
	struct dirent *dirres = NULL;
	static struct stat statbuff;
	char destDirName[NAMESIZE] = {0};
	int ret = 0;

	ret = stat(srcName, &statbuff);
	if (ret < 0)
	{
		perror("lstat()");
		exit(1);
	}

	if ((statbuff.st_mode & S_IFMT) != S_IFDIR)
	{
		struct Node data;		
		struct fileNode *node = malloc(sizeof(*node));
		if (node == NULL)
		{
			perror("malloc()");
			exit(1);
		}
		
		strcpy(node->src, srcName);
		strcpy(node->dest, destName);

		
		data.fileTask = myCopy;
		strcpy(data.args.src, node->src);
		strcpy(data.args.dest, node->dest);
		addTask(&pool, data);	

		return ;
	}
	
	mkdir(destName, 0777);
	
	dir = opendir(srcName);
	if (dir == NULL)
	{
		perror("opendir()");
		exit(1);
	}

	char fileName[NAMESIZE] = {0};
	while ((dirres = readdir(dir)) != NULL)
	{
		sprintf(fileName, "%s/%s", srcName, dirres->d_name);
		if (is_loop(fileName) == 0)
		{
			sprintf(destDirName, "%s/%s", destName, dirres->d_name);
			func(fileName, destDirName);
		}
	}

	closedir(dir);
	return ;
}

int main(int argc,char **argv)
{
	if (argc < 3)
	{
		fprintf(stdout, "usage:\n");
		exit(1);
	}
	
	initPool(&pool, PTHREADNUM);

	func(argv[1], argv[2]);
	
	destroyPool(&pool);

    exit(0);
}
